<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="searchUser" />
        <!-- 树形组件 -->
        <el-tree ref="tree" :data="data" :props="defaultProps" :expand-on-click-node="false" highlight-current default-expand-all node-key="id" @current-change="treeChange" />

      </div>
      <div class="right">

        <el-row type="flex" justify="end">
          <el-button class="opeate-tools" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button class="opeate-tools" size="mini" @click="visible =true">excel导入</el-button>
          <el-button class="opeate-tools" size="mini" @click="excelExport">excel导出</el-button>
        </el-row>

        <el-table :data="list" style="width: 100%">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :size="35" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" align="center" />
          <el-table-column prop="mobile" label="手机号" sortable align="center" />
          <el-table-column prop="workNumber" label="工号" sortable align="center" />
          <el-table-column prop="formOfEmployment" label="聘用形式" align="center">
            <template #default="{row}">
              <span v-if="row.formOfEmployment ===1">正式</span>
              <span v-else-if="row.formOfEmployment ===2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" align="center" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable align="center" />
          <el-table-column label="操作" align="center">
            <template #default="{row}">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" style="margin-right: 8px;" @click="roleBtn(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" align="middle" justify="end" style="height: 60">
          <el-pagination layout="total, prev, pager, next" :total="total" @current-change="pageChange" />
        </el-row>
      </div>
    </div>
    <!-- 添加excel 组件 -->
    <addExcel :visible.sync="visible" @onSucceed="getEmployeeList" />
    <!-- 修改角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <!-- 绑定员工 分配角色的id 打开弹框自动勾选上 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in checkList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="roleChange">确 定</el-button>
          <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        </el-row>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import addExcel from './components/add-excel.vue'
import { departmentAPI } from '@/api/department'
import { changeRoleAPI, delEmployeeAPI, employeeDetailAPI, enableRoleAPI, excelExportAPI, getEmployeeAPI } from '@/api/employee'
import { tree2List } from '@/utils'
import FileSaver from 'file-saver'
export default {
  name: 'Employee',
  components: { addExcel },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      depid: null,
      pagesize: 10,
      page: 1,
      keyword: '',
      total: null,
      list: [],
      visible: false,
      dialogVisible: false,
      checkList: [],
      roleIds: []
    }
  },
  async created() {
    // 调用部门列表接口
    const res = await departmentAPI()
    // 复用 递归树状遍历数据
    this.data = tree2List(res.data.data)
    // 初始化时 depid存为最上一层
    this.depid = this.data[0].id

    this.getEmployeeList()
    // 等DOM 渲染成功后 在把样式高亮渲染上去
    this.$nextTick(() => {
      this.$refs.tree.setCurrentKey(this.data[0].id)
    })
  },
  methods: {
    async getEmployeeList() {
      // 获取员工列表数据
      const res = await getEmployeeAPI({
        departmentId: this.depid,
        page: this.page,
        pagesize: this.pagesize,
        keyword: this.keyword
      })
      // 把获取到数据存进数组里面
      this.list = res.data.data.rows
      // 获取总页数
      this.total = res.data.data.total
    },
    treeChange(data) {
      // 每点击树里面部门 刷新员工数据都到第一页
      this.page = 1
      // 更改部门后 把id存进 depid中
      this.depid = data.id
      // 重新渲染数据
      this.getEmployeeList()
    },
    pageChange(page) {
      // 分页器的页面刷新数据
      this.page = page
      this.getEmployeeList()
    },
    searchUser() {
      // 员工模糊搜索
      // 用防抖的方法
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.getEmployeeList()
      }, 1000)
    },
    async excelExport() {
      // 接收拦截器里面 返回 blob 格式数据
      const res = await excelExportAPI()
      // 打印出 excel 文件
      FileSaver.saveAs(res, '员工列表数据.xlsx')
      // console.log(123, res)
    },
    async delEmployee(id) {
      const res = await delEmployeeAPI(id)

      this.$message.success(res.data.message)
      // 当页数只有一个人时候,删除页数减一    只有一页就不会减一
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.getEmployeeList()
    },
    async roleBtn(id) {
      this.id = id
      // 获取员工里面所有角色
      const res1 = await enableRoleAPI()
      this.checkList = res1.data.data
      // 获取员工详情
      const res2 = await employeeDetailAPI(id)
      this.roleIds = res2.data.data.roleIds

      this.dialogVisible = true
    },
    async roleChange() {
      // 调用修改角色接口
      const res = await changeRoleAPI({
        id: this.id,
        roleIds: this.roleIds
      })

      this.dialogVisible = false
      this.$message.success(res.data.message)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
